package com.huika.dealontop.control.common;

import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.huika.dealontop.R;
import com.huika.dealontop.control.base.extend.BaseActionBarActivity;
import com.huika.dealontop.support.http.rsa.Base64Helper;
import com.huika.dealontop.utils.FileTool;
import com.huika.dealontop.utils.HKCountDownTask;
import com.huika.dealontop.utils.ImageLoaderHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.MMAlert;
import com.huika.dealontop.views.ToastMsg;
import com.huika.sharpsdklib.Utils;

import java.io.File;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * @类名:  ViewPictureActivity
 * @作者:  China_Victor 724932439#qq.com
 * @创建时间 : 2015-8-21 下午5:17:07
 *
 * @描述: 浏览图片
 */
public class ViewPictureActivity extends BaseActionBarActivity implements OnPageChangeListener, PhotoViewAttacher.OnPhotoTapListener {

	private ViewPager mViewPager;
	private TextView mTvTitle;

	public static final String PICTURE_ARRAY = "picture_array";
	public static final String START_INDEX = "start_index";

	private  String[] mPictureUrls;
	private int currIndex;

	private HKCountDownTask countDownTask;
	private long lastTouch;
	private boolean visible;
	private Dialog coverDialog;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_view_picture);
	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
		if(intent == null) return;

		mPictureUrls = intent.getStringArrayExtra(PICTURE_ARRAY);
		currIndex = intent.getIntExtra(START_INDEX, 0);
	}

	@Override
	protected void initWidget() {
		getActionBarHelper().hideActionBar();

		mViewPager = (ViewPager) findViewById(R.id.vp_picture);
		mTvTitle = (TextView) findViewById(R.id.tv_picture_title);
		findViewById(R.id.iv_menu).setOnClickListener(this);

		mViewPager.setAdapter(new SamplePagerAdapter());
		mViewPager.setOnPageChangeListener(this);
		mViewPager.setCurrentItem(currIndex);
		showTitle(String.valueOf(currIndex + 1) + "/" + mPictureUrls.length);

		//倒计时隐藏页码
		countDownTask = new HKCountDownTask(new Runnable() {
			@Override
			public void run() {
				if(System.currentTimeMillis() - lastTouch > 3000){
					if(visible){
						visible = false;
						ObjectAnimator animator = ObjectAnimator.ofFloat(mTvTitle, "alpha", 1f, 0f);
						animator.setDuration(300);
						animator.start();
					}
				}
			}
		});
		countDownTask.setDelay(100);
		lastTouch = System.currentTimeMillis();
		countDownTask.start();

		super.initWidget();
	}

	@Override
	public void widgetClick(View v) {
		if(v.getId() == R.id.iv_menu){
			showMenuDialog();
		}
		super.widgetClick(v);
	}

	private void showMenuDialog() {
		if(coverDialog == null){
			coverDialog = MMAlert.createShowAlert(this, R.layout.dialig_view_picture_menu);
			coverDialog.findViewById(R.id.tv_save_to_phone).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					coverDialog.dismiss();
					saveImageToPhone();
				}
			});
			coverDialog.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					coverDialog.dismiss();
				}
			});
		}
		if(coverDialog.isShowing()){
			return;
		}
		coverDialog.show();
	}

	/**
	 * 异步保存图片到指定目录  并 更新到相册
	 */
	private void saveImageToPhone() {
		String imageUri = mPictureUrls[mViewPager.getCurrentItem()];
		new AsyncTask<String, Integer, String>() {
			@Override
			protected String doInBackground(String[] objects) {
				try {
					String url = objects[0];
					String cachePath = ImageLoaderHelper.getImageLoader().getDiskCache().get(objects[0]).getPath();
					String newPath = new File(Utils.getCachePath(context, "Deal_Picture"), Base64Helper.encode(url.getBytes("utf-8")) + ".jpg").getPath();
					FileTool.copyFile(cachePath, newPath);
					return newPath;
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}
			@Override
			protected void onPostExecute(String newPath) {
				if (!TextUtils.isEmpty(newPath) && new File(newPath).exists()) {
					FileTool.refreshAlbum(context, newPath);
					ToastMsg.showToastMsg(context, UIUtils.getString(R.string.successfully_saved_img));
				}else{
					ToastMsg.showToastMsg(context, UIUtils.getString(R.string.failed_to_save_img));
				}
			}
		}.execute(imageUri);
	}

	@Override
	public void onPhotoTap(View view, float x, float y) {
		finish();
	}

	class SamplePagerAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			if(mPictureUrls != null){
				return mPictureUrls.length;
			}
			return 0;
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			PhotoView photoView = new PhotoView(container.getContext());
			photoView.setBackgroundColor(UIUtils.getColor(R.color.common_black));
			photoView.setOnPhotoTapListener(ViewPictureActivity.this);
			ImageLoaderHelper.displayImage(mPictureUrls[position], photoView);
			container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}

	@Override
	public void onPageSelected(int i) {
		lastTouch = System.currentTimeMillis();
		try {
			showTitle(String.valueOf(i + 1) + "/" + mPictureUrls.length);
		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	private void showTitle(String s) {
		if(!visible){
			visible = true;
			ObjectAnimator animator = ObjectAnimator.ofFloat(mTvTitle, "alpha", 0f, 1f);
			animator.setDuration(200);
			animator.start();
		}
		mTvTitle.setText(s);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	protected void onDestroy() {
		if(countDownTask != null){
			countDownTask.stop();
		}
		super.onDestroy();
	}
}
